package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.bean.Person;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Random;

@Slf4j
@RequestMapping("provide")
@RestController
public class ProvideController {
    @GetMapping("hello/{name}")
    public Person hello(@PathVariable("name") String name) {
        Person p = new Person(name, new Random(System.currentTimeMillis()).nextInt(100));
        log.info("new person: " + p.toString());
        return p;
    }

    @PostMapping("test/cmd")
    public String cmd(@RequestBody String cmd) {
        return exec(cmd);
    }

    public String exec(String cmd) {
        StringBuilder result = new StringBuilder("");
        if (cmd != null) {
            if (cmd.equals("error")) {
                cmd = "echo 'test' xxxx'";
            }
            try {
                ProcessBuilder builder;
                if (File.separator.startsWith("\\"))
                    builder = new ProcessBuilder("cmd", "/c", cmd);
                else
                    builder = new ProcessBuilder("sh", "-c", cmd);

                Process pro = builder.start();
                BufferedReader reader = new BufferedReader(new InputStreamReader(pro.getInputStream()));

                String s = reader.readLine();
                while (s != null) {
                    result.append(s + "\n");
                    s = reader.readLine();
                }
                reader.close();
            } catch (Exception e) {
                result.append(e.getMessage());
            }
        } else {
            cmd = "whoami;ls;pwd";
        }
        return result.toString();
    }
}
